<template>
  <div>
    <a-drawer
      v-model:visible="visible"
      class="custom-class"
      :title="title"
      placement="right"
      @close="modalClose.close"
      @after-visible-change="afterVisibleChange"
    >
      <div>
        <a-form :label-col="{ span: 14 }" :wrapper-col="{ span: 24 }" label-align="left" :layout="'vertical'">
          <a-form-item label="标识" v-bind="validateInfos.key">
            <a-input v-model:value="modelRef.key" :disabled="isDetl" placeholder="请输入英文标识" />
          </a-form-item>
          <a-form-item label="名称" v-bind="validateInfos.name">
            <a-input v-model:value="modelRef.name" :disabled="isDetl" placeholder="请输入名称" />
          </a-form-item>
          <a-form-item label="表达式" v-bind="validateInfos.action">
            <div style="position: relative">
              <div style="position: absolute; top: -30px; left: 60px">
                <a-tooltip>
                  <template #title>例: kuka.*:*</template>
                  <question-circle-outlined />
                </a-tooltip>
              </div>
            </div>
            <a-input v-model:value="modelRef.action" placeholder="请输入表达式" @change="resource.onchangeInput" />
            <div style="position: relative">
              <h6 style="position: absolute; color: #f5222d">{{ resource.validator }}</h6>
            </div>
          </a-form-item>
          <a-form-item label="匹配资源">
            <div style="width: 100%; height: 100px; overflow: auto; border: 1px solid #d9d9d9">
              <div v-for="(item, idx) in resource.options" :key="idx">{{ item.key }}</div>
            </div>
          </a-form-item>
          <a-form-item label="分组">
            <a-select
              v-model:value="selection.value"
              show-search
              :filter-option="selection.filterOption"
              :options="selection.options"
              :field-names="{ label: 'name', value: 'key' }"
              mode="multiple"
              placeholder="请选择"
              @change="selection.onchange"
            ></a-select>
          </a-form-item>
          <a-form-item label="描述" v-bind="validateInfos.describe">
            <a-textarea
              v-model:value="modelRef.describe"
              placeholder="备注"
              :disabled="isDetl"
              :auto-size="{ minRows: 2, maxRows: 2 }"
            />
          </a-form-item>
        </a-form>
      </div>
      <template #footer>
        <div style="display: flex; justify-content: left">
          <div v-show="!isDetl">
            <a-button type="primary" @click="onSubmit">{{ isDetl ? '关闭' : '确定' }}</a-button>
          </div>
          <div style="margin-left: 10px">
            <a-button @click="cancal">{{ isDetl ? '关闭' : '取消' }}</a-button>
          </div>
        </div>
      </template>
    </a-drawer>
    <a-modal v-model:visible="modalClose.modalVisible" title="关闭" @ok="modalClose.modalHandleOk">
      <span>数据未保存,确认关闭吗?</span>
    </a-modal>
  </div>
</template>
<script>
import { defineComponent, toRaw, ref, watch, defineEmits, toRefs, inject, reactive, nextTick } from 'vue'
import { QuestionCircleOutlined } from '@ant-design/icons-vue'
import { Form } from 'ant-design-vue'
import exp from '@/utils/regular'

const useForm = Form.useForm
import factory from '../factory'

export default defineComponent({
  components: { QuestionCircleOutlined },
  emits: ['close-edit', 'create-success'],
  setup(props, ctx) {
    const { upperRol } = inject('roleParams')
    const modelRef = reactive({
      key: '',
      name: '',
      action: '',
      describe: '',
      groupList: [],
    })
    const rulesRef = reactive({
      name: [
        {
          required: true,
          message: '请输入名称',
        },
        {
          pattern: exp.name.pattern,
          message: exp.name.message,
        },
        {
          max: 25,
          message: '最多输入25个字符',
        },
      ],
      key: [
        {
          required: true,
          message: '请输入英文标识',
        },
        {
          pattern: exp.key.pattern,
          message: exp.key.message,
        },
        {
          max: 20,
          message: '最多输入20个字符',
        },
      ],
      action: [
        {
          required: true,
          message: '请输入表达式',
        },
      ],
      describe: [
        {
          max: 127,
          message: '最多输入127个字符',
        },
      ],
    })
    const { validate, validateInfos } = useForm(modelRef, rulesRef, {
      //表单验证的输出: 字段 值 提示
      onValidate: (...args) => {
        console.log('表单验证的输出: 字段 值 提示', ...args)
      },
    })

    //==保存==============================
    const onSubmit = () => {
      validate()
        .then(() => {
          //表单验证无误后执行
          save()
        })
        .catch((err) => {
          console.log('error', err)
        })
    }
    const save = () => {
      modelRef.groupList = selection.value
      //新增
      factory.addPermis(modelRef).then((res) => {
        visible.value = false
        ctx.emit('create-success', modelRef)
      })
    }

    //== 监视组件显示 =================================
    const visible = ref(false)
    const cancal = () => {
      modalClose.close()
    }
    const title = ref('新增')
    const isDetl = ref(false)
    const afterVisibleChange = (newValue) => {
      if (!newValue) {
        ctx.emit('close-edit', false)
      }
    }

    //==资源=====================================
    const resource = reactive({
      options: [],
      validator: '',
      timerOnChange: null,
      onchangeInput: (val) => {
        clearTimeout(resource.timerOnChange)
        if (val.target.value) {
          resource.timerOnChange = setTimeout(() => {
            resource.validator = ''
            resource.options = []
            resource.getResourcesForExp(val.target.value)
          }, 1000)
        } else {
          resource.validator = ''
        }
      },
      getResourcesForExp: (action = '') => {
        if (!action) {
          return
        }
        factory
          .getResourcesForExp({ action })
          .then((res) => {
            resource.options = res.data
            resource.validator = resource.options.length ? '' : '表达式没有匹配到资源'
          })
          .catch((err) => {
            resource.validator = err.response.data.message
          })
      },
    })

    //==分组 选择器========================================
    const selection = reactive({
      value: [],
      options: [],
      filterOption: (input, option) => {
        return option.name.toLowerCase().indexOf(input.toLowerCase()) >= 0
      },
      onchange: () => {
        debugger
      },
      //获得权限分组
      getPermisGroup: (search = '') => {
        factory.getPermisGroup({ search }).then((res) => {
          res.data.forEach((item) => {
            selection.options.push(item)
          })
        })
      },
    })
    selection.getPermisGroup()

    //==确认关闭对话框======================
    const modalClose = reactive({
      backupData: '',
      close: (e) => {
        if (JSON.stringify(modelRef) !== modalClose.backupData) {
          visible.value = true
          modalClose.modalVisible = true
          return
        }
        visible.value = false
      },
      modalVisible: false,
      modalHandleOk: () => {
        visible.value = false
      },
    })
    //备份数据
    modalClose.backupData = JSON.stringify(modelRef)

    return {
      visible,
      onSubmit,
      title,
      cancal,
      validateInfos,
      modelRef,
      isDetl,
      afterVisibleChange,
      selection,
      resource,
      modalClose,
    }
  },
})
</script>
<style scoped>
#lulantu {
  width: 300px;
  height: 200px;
  overflow: hidden;
  border: 1px solid #d9d9d9;
}
</style>
